package com.itheima.web;

import com.itheima.pojo.Item;
import com.itheima.pojo.User;
import com.itheima.service.ItemService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/addGoodsServlet")
public class AddGoodsServlet extends HttpServlet {
    private ItemService service = new ItemService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String itemName = request.getParameter("itemName");
        String description = request.getParameter("description");
        String price = request.getParameter("price");
        String inventory = request.getParameter("inventory");

        Item item = new Item();
        item.setItemName(itemName);
        item.setDescription(description);
        item.setPrice(Integer.valueOf(price));
        item.setInventory(Integer.valueOf(inventory));

        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        String sellerName = user.getUsername();
        Integer sellerId = user.getId();
        item.setSellerName(sellerName);
        item.setSellerId(sellerId);

        service.add(item);

        response.sendRedirect("myStoreServlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
